package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.ResultFactory;
import com.itheima.common.exception.BusinessException;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean save(User user) {
        return userMapper.save(user);
    }

    @Override
    public boolean update(User user) {
        return userMapper.update(user);
    }

    @Override
    public boolean delete(Integer uuid) {
        return userMapper.delete(uuid);
    }

    @Override
    @Transactional(readOnly = true)
    public User get(Integer uuid) {
        return userMapper.get(uuid);
    }

    @Override
    public Page<User> getAll(Integer page, Integer size) {

        PageHelper.startPage(page, size);
        Page<User> pageList = (Page<User>) userMapper.getAll();

        return pageList;
    }

    @Override
    public Page<User> getUsers(User user, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        Page<User> pageList = (Page<User>) userMapper.getUsers(user);
        return pageList;
    }

    @Override
    public User login(String userName, String password) {

        if (StringUtils.isEmpty(userName)) {
            throw new BusinessException(ResultFactory.ERROR("用户名不能为空"));
        }
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException(ResultFactory.ERROR("密码不能为空"));
        }

        User user = userMapper.getByUserNameAndPassword(userName, password);

        if (user == null) {
            throw new BusinessException(ResultFactory.ERROR("用户名或密码错误"));
        }

        return user;
    }
}
